<template>
  <div class="callback-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-section">
      <div class="loading-spinner"></div>
      <p class="loading-text">正在处理钉钉登录...</p>
    </div>

    <!-- 成功状态 -->
    <div v-else-if="loginSuccess" class="success-section">
      <div class="success-icon">✓</div>
      <h2 class="success-title">登录成功！</h2>
      <div class="user-info">
        <img :src="userInfo.avatar_url || '/default-avatar.png'" :alt="userInfo.name || '用户'" class="user-avatar" />
        <div class="user-details">
          <p class="user-name">{{ userInfo.name || '钉钉用户' }}</p>
          <p class="user-id">ID: {{ userInfo.id }}</p>
          <p v-if="userInfo.mobile" class="user-mobile">手机号: {{ userInfo.mobile }}</p>
          <p v-if="userInfo.email" class="user-email">邮箱: {{ userInfo.email }}</p>
        </div>
      </div>
      <div class="success-actions">
        <van-button
          type="primary"
          size="large"
          class="continue-btn"
          @click="handleContinue"
        >
          继续使用
        </van-button>
        <van-button
          size="large"
          class="logout-btn"
          @click="handleLogout"
        >
          切换账号
        </van-button>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-section">
      <div class="error-icon">✕</div>
      <h2 class="error-title">登录失败</h2>
      <p class="error-message">{{ errorMessage }}</p>
      <div class="error-actions">
        <van-button
          type="primary"
          size="large"
          class="retry-btn"
          @click="handleRetry"
        >
          重试
        </van-button>
        <van-button
          size="large"
          class="back-btn"
          @click="handleBackToLogin"
        >
          返回登录页
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showSuccessToast } from 'vant'

const router = useRouter()
const route = useRoute()

const loading = ref(true)
const loginSuccess = ref(false)
const errorMessage = ref('')
const userInfo = ref({})
const accessToken = ref('')

const handleDingtalkCallback = async () => {
  try {
    const { code, state, authCode } = route.query

    // 兼容处理钉钉回调参数（钉钉可能返回 code 或 authCode）
    const authCodeParam = code || authCode

    if (!authCodeParam || !state) {
      throw new Error('缺少必要的授权参数')
    }

    // 验证state参数
    const storedState = localStorage.getItem('dingtalk_state')
    if (state !== storedState) {
      throw new Error('状态验证失败，可能存在安全风险')
    }

    // 调用后端处理回调
    const response = await fetch(`http://localhost:8000/api/auth/dingtalk/callback?code=${authCodeParam}&state=${state}`)
    const data = await response.json()

    if (data.success) {
      // 存储用户信息和访问令牌
      localStorage.setItem('access_token', data.access_token)
      localStorage.setItem('user_info', JSON.stringify(data.dingding_user))
      localStorage.setItem('login_platform', 'dingtalk')

      userInfo.value = data.dingding_user
      accessToken.value = data.access_token
      loginSuccess.value = true
      showSuccessToast('钉钉登录成功！')
    } else {
      throw new Error(data.message || '登录失败')
    }
  } catch (err) {
    console.error('钉钉回调处理错误:', err)
    errorMessage.value = err.message || '登录过程中发生错误'
    showToast(errorMessage.value)
  } finally {
    loading.value = false
  }
}

const handleContinue = () => {
  // 跳转到主页或其他页面
  router.push('/')
}

const handleLogout = async () => {
  try {
    const token = localStorage.getItem('access_token')
    if (token) {
      await fetch(`http://localhost:8000/api/auth/logout?token=${token}`, {
        method: 'POST'
      })
    }

    // 清除本地存储
    localStorage.removeItem('access_token')
    localStorage.removeItem('user_info')
    localStorage.removeItem('login_platform')
    localStorage.removeItem('dingtalk_state')

    // 返回登录页
    router.push('/login')
  } catch (error) {
    console.error('登出错误:', error)
    // 即使登出失败也清除本地存储
    localStorage.removeItem('access_token')
    localStorage.removeItem('user_info')
    localStorage.removeItem('login_platform')
    localStorage.removeItem('dingtalk_state')
    router.push('/login')
  }
}

const handleRetry = () => {
  // 重新加载页面以重试
  window.location.reload()
}

const handleBackToLogin = () => {
  router.push('/login')
}

onMounted(() => {
  handleDingtalkCallback()
})
</script>

<style scoped>
.callback-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.loading-section,
.success-section,
.error-section {
  background-color: white;
  border-radius: 12px;
  padding: 40px 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 400px;
  width: 100%;
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #4A90E2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.success-icon,
.error-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  font-size: 30px;
  font-weight: bold;
}

.success-icon {
  background-color: #4CAF50;
  color: white;
}

.error-icon {
  background-color: #f44336;
  color: white;
}

.success-title,
.error-title {
  color: #333;
  font-size: 24px;
  margin: 0 0 20px 0;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
}

.user-details {
  flex: 1;
  text-align: left;
}

.user-name {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin: 0 0 5px 0;
}

.user-id,
.user-mobile,
.user-email {
  font-size: 14px;
  color: #666;
  margin: 2px 0;
}

.success-actions,
.error-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.continue-btn,
.retry-btn {
  background-color: #4A90E2;
  border: none;
  border-radius: 8px;
  height: 44px;
  font-size: 16px;
}

.logout-btn,
.back-btn {
  background-color: transparent;
  border: 1px solid #ddd;
  color: #666;
  border-radius: 8px;
  height: 44px;
  font-size: 16px;
}

.error-message {
  color: #f44336;
  font-size: 16px;
  margin: 0 0 30px 0;
  line-height: 1.5;
}
</style>
